package controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import pojo.Sanpham;
import util.MessageNotificationHepler;
import util.SearchVisitor;
import dao.SanphamDAO;

@ManagedBean (name="quanLySanPhamBean")
@ViewScoped
public class QuanLySanPhamBean implements Serializable{

	private static final long serialVersionUID = 1L;
	private List<Sanpham> lstSanPham;
	private String chuoiTimKiem;
	private int maLoaiLietKe; // dùng cho action Liệt kê
	
	@PostConstruct
	public void init() {
		setLstSanPham(new ArrayList<Sanpham>());
		
	}

	public List<Sanpham> getLstSanPham() {
		return lstSanPham;
	}

	public void setLstSanPham(List<Sanpham> lstSanPham) {
		this.lstSanPham = lstSanPham;
	}
	
	public void LietKeToanBo()
	{
		SanphamDAO spdao = new SanphamDAO();
		lstSanPham = spdao.getList();
	}

	public void LietKeTheoLoai()
	{
		System.out.println("Liet Ke Loai: " + getMaLoaiLietKe());
		SanphamDAO spdao = new SanphamDAO();
		lstSanPham = spdao.GetSanPhamTheoMaLoai(getMaLoaiLietKe());
				
	}
	public void TimKiem()
	{
		System.out.println("Tim Kiếm: ");
		SanphamDAO spdao = new SanphamDAO();
		SearchVisitor sv = new SearchVisitor();
		spdao.accept(sv, getChuoiTimKiem(), 0, -1);
		lstSanPham = sv.getResultSanPham();
		System.out.println("Tim Kiếm KQ: " + lstSanPham.size());
	}	

	public void Xoa(Sanpham sp)
	{
		System.out.println("Xóa: " + sp.getMasanpham());
		SanphamDAO spdao = new SanphamDAO();
		//spdao.delete(sp);
		sp.setDaxoa(true);
		spdao.saveOrUpdate(sp);
		ClearLstSanPham();				

		MessageNotificationHepler.ShowMessage(String.format(
				"Sản phẩm '%s' đã được xóa thành công!",
				sp.getTensanpham()));
	}
	public void HuyXoa(Sanpham sp)
	{
		System.out.println("Xóa: " + sp.getMasanpham());
		SanphamDAO spdao = new SanphamDAO();
		//spdao.delete(sp);
		sp.setDaxoa(false);
		spdao.saveOrUpdate(sp);
		ClearLstSanPham();
		
		MessageNotificationHepler.ShowMessage(String.format(
				"Sản phẩm '%s' đã được phục hồi thành công!",
				sp.getTensanpham()));
	}		
	
	private void ClearLstSanPham()
	{
		getLstSanPham().clear();
	}
	
	
	/**
	 * @return the chuoiTimKiem
	 */
	public String getChuoiTimKiem() {
		return chuoiTimKiem;
	}

	/**
	 * @param chuoiTimKiem the chuoiTimKiem to set
	 */
	public void setChuoiTimKiem(String chuoiTimKiem) {
		this.chuoiTimKiem = chuoiTimKiem;
	}

	/**
	 * @return the maLoaiLietKe
	 */
	public int getMaLoaiLietKe() {
		return maLoaiLietKe;
	}

	/**
	 * @param maLoaiLietKe the maLoaiLietKe to set
	 */
	public void setMaLoaiLietKe(int maLoaiLietKe) {
		this.maLoaiLietKe = maLoaiLietKe;
	}


}
